/*
 * MyStack.c
 *
 *  Created on: Jan 28, 2012
 *      Author: Georgios
 */

#include <stdio.h>
#include <stdlib.h>
//#include <conio.h>

#include "MyStack.h"

/*
 ** Initialize an empty stack.
 ** Return 0 if not initialized
 */
int StackInit(stack_t *stackP, int maxSize) {
  stackElement_t *newContents = NULL;

  /* Allocate a new array to hold the contents. */
  newContents = (stackElement_t *)malloc(sizeof(stackElement_t)
                                        * maxSize);

  if (newContents == NULL) {
    fprintf(stderr, "Insufficient memory to initialize stack.\n");
    return 0;  /* Return false. */
  }

  stackP->contents = newContents;
  stackP->maxSize = maxSize;
  stackP->top = -1;  /* I.e., empty */
  return 1; /* Return true. */
}


/*
 ** Destroy the stack.
 */
void StackDestroy(stack_t *stackP) {
  /* Get rid of array. */
  free(stackP->contents);

  stackP->contents = NULL;
  stackP->maxSize = 0;
  stackP->top = -1;  /* I.e., empty */
}


/* Check the stack if empty*/
int StackIsEmpty(stack_t *stackP) {
	return stackP->top < 0;
}


/* Check the stack if full*/
int StackIsFull(stack_t *stackP) {
	return stackP->top >= stackP->maxSize - 1;
}


/*
 ** Push one element to the stack
*/
int StackPush(stack_t *stackP, stackElement_t element) {
  if (StackIsFull(stackP)) {
    fprintf(stderr, "Can't push element on stack: stack is full.\n");
    return 0;  /* Returning error code. */
  }

  /* Put information in array; update top. */

  stackP->contents[++stackP->top] = element;
  return 1;
}


/*
 ** Pop one element from the stack
*/
stackElement_t *StackPop(stack_t *stackP) {
  if (StackIsEmpty(stackP)) {
    fprintf(stderr, "Can't pop element from stack: stack is empty.\n");
    return NULL;  /* return NULL. */
  }

  return &(stackP->contents[stackP->top--]);
}
